<template>
  <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="mengli-commerce-order min-fill-page">
    <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
      <FilterTool
        ref="FilterToolRef"
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
        @filterTagStatus="filterTagStatus"
      />
      <div class="opeator-bar">
        <createBtn
          v-if="hasRouteAuth('mengli:afterSale:edit') || isAdmin"
          style="margin-right:14px;"
          @click.native="toCreate" />
        <MoreOpeator
          ref="moreOpeatorRef"
          :list="[
            {label:'导出', type: 'export', auth: hasRouteAuth('mengli:afterSale:export'), exportApi:'/admin/mengli/afterSales/export',
             exportName:'电商售后', isBeforeExport:true, beforeExport: exportBeforeExport, refName:'projectExportRef'},
            {label:'导入售后单', type: 'import', auth:hasRouteAuth('mengli:afterSale:import'), importApi:'/admin/mengli/afterSales/order/import', callback:fetchData},
            {label:'导入物流成本', type: 'import', auth:hasRouteAuth('mengli:afterSale:import'), importApi:'/admin/mengli/afterSales/cost/import', callback:fetchData},
            {label:'物流成本模板下载', type: 'export', exportApi:'/admin/mengli/afterSales/costTemplate', exportName:'物流信息模板'}
          ]"
          label="更多操作"
          style="margin-right:14px;"
        />
      </div>
    </div>
    <div v-loading="listLoading" style="min-height: 300px;">
      <u-table
        v-if="list.items.length > 0"
        ref="afterSaleRef"
        :data="list.items"
        :row-class-name="tableRowClassName"
        :height="setTableHeight"
        :row-height="rowHeight()"
        :border="true"
        beautify-table
        header-drag-style
        use-virtual
        element-loading-text="加载中..."
        empty-text="暂无数据"
        class="fb-table"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row
        @sort-change="sortMethod"
        @select="selectTable"
        @select-all="selectTable">
        <u-table-column
          align="center"
          type="selection"
          fixed
          width="50"/>
        <u-table-column align="left" label="退货编号(系统)" width="210">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.systemSn" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.systemSn }}</div>
              <div class="ellipsis light-word" @click="toDetail(scope.row)">{{ scope.row.systemSn }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="退货编号(淘宝)" width="120">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.taobaoSn" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.taobaoSn }}</div>
              <div class="ellipsis light-word" @click="toDetail(scope.row)">{{ scope.row.taobaoSn }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="订单编号" width="220">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.orderNum" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.orderNum }}</div>
              <div class="ellipsis light-word" @click="toCommerceOrder(scope.row)">{{ scope.row.orderNum }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="SKU编码" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.goodsCoding" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="仓库" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.warehouse" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="标题" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.title" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="退货商品数量" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.number" />
          </template>
        </u-table-column>
        <u-table-column align="right" label="交易金额(元)" min-width="110">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.payAmount" :price="scope.row.payAmount / 100" />
          </template>
        </u-table-column>
        <u-table-column align="right" label="退款金额(元)" min-width="110">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.backAmount" :price="scope.row.backAmount / 100" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="原因" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.reason" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="部分退款/全部退款" min-width="140">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.partialOrFullrefund | formatRebates" />
          </template>
        </u-table-column>
        <u-table-column align="right" label="物流成本(元)" min-width="110">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.cost" :price="scope.row.cost / 100" />
          </template>
        </u-table-column>
        <u-table-column align="right" label="仓库收件费(元)" min-width="120">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.warehouseFees" :price="scope.row.warehouseFees / 100" />
          </template>
        </u-table-column>
        <u-table-column align="right" label="其他费用(元)" min-width="110">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.otherFees" :price="scope.row.otherFees / 100" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="发货单号" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.logisticsNumber" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="发货时间" min-width="160">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.deliveryTime" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="退款状态" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.refundsStatus | formatRefundsStatus" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="退货状态" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.returnsStatus | formatReturnGoods" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="货物状态" min-width="110">
          <template slot-scope="scope">
            <span class="light-word" @click="openDealDialog(scope.row)">{{ scope.row.goodsStatus | formatGoodsStatus }}</span>
          </template>
        </u-table-column>
        <u-table-column align="left" label="处理状态" min-width="110">
          <template slot-scope="scope">
            <span class="light-word" @click="openDealDialog(scope.row)">{{ scope.row.dealStatus | formatDealStatus }}</span>
          </template>
        </u-table-column>
        <u-table-column align="left" label="创建人" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.creator || '--' }}</span>
          </template>
        </u-table-column>
        <u-table-column align="left" label="创建时间" min-width="160">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.createTime" />
          </template>
        </u-table-column>
        <u-table-column align="left" width="110" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="toDetail(scope.row)"><span style="font-size:14px;">查看</span></el-button>
            <el-dropdown trigger="click">
              <div class="el-dropdown-link">
                <el-button type="text"><span style="font-size:14px;">更多<i class="el-icon-arrow-down"/></span></el-button>
              </div>
              <el-dropdown-menu slot="dropdown" style="margin-top:-24px;margin-right:15px;padding: 0;">
                <el-dropdown-item :disabled="!hasRouteAuth('mengli:afterSale:edit')" style="width:100px;text-align: center" @click.native="toEdit(scope.row)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item :disabled="!([0, 1].includes(scope.row.dealStatus))" style="width:100px;text-align: center" @click.native="handelDelete(scope.row.id)">
                  <div>删除</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </u-table-column>
      </u-table>
      <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
    </div>
    <el-row v-if="showMobilePage && list && list.total > 0" type="flex" justify="left">
      <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
      <el-pagination
        v-show="list.total > 0"
        :current-page="list.page"
        :page-size="list.perPage"
        :total="list.total"
        :page-sizes="[20, 50, 100, 250, 500]"
        :layout="pageLayout"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>
    <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
      <template v-if="showMobilePage">
        <FilterTool
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          show-mobile-icon
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"
        />
        <MoreOpeator
          ref="moreOpeatorRef"
          :list="[
            {label:'导出', type: 'export', auth: hasRouteAuth('mengli:afterSale:export'), exportApi:'/admin/mengli/afterSales/export',
             exportName:'电商售后', isBeforeExport:true, beforeExport: exportBeforeExport, refName:'projectExportRef'},
            {label:'导入售后单', type: 'import', auth:hasRouteAuth('mengli:afterSale:import'), importApi:'/admin/mengli/afterSales/order/import', callback:fetchData},
            {label:'导入物流成本', type: 'import', auth:hasRouteAuth('mengli:afterSale:import'), importApi:'/admin/mengli/afterSales/cost/import', callback:fetchData},
            {label:'物流成本模板下载', type: 'export', exportApi:'/admin/mengli/afterSales/costTemplate', exportName:'物流信息模板'},
            {label:'批量退货处理', handelClick: batchReturn},
          ]"
          show-mobile-icon
        />
        <createBtn
          v-if="hasRouteAuth('mengli:afterSale:edit') || isAdmin"
          mobile-table
          @click.native="toCreate" />
      </template>
      <template v-else>
        <div class="batch-operation">
          <el-button size="mini" @click="batchReturn">批量退货处理</el-button>
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        </div>
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </template>
    </fixed-pagination>

    <DealDialog
      :dialog-visible="showDealDialog"
      :is-batch-handel="isBatchHandel"
      v-model="dealData"
      @closeDealDialog="closeDealDialog"
      @openRecordDialog="openRecordDialog"
    />
    <RecordDialog :dialog-visible="showRecordDialog" v-model="recordData" @closeRecordDialog="closeRecordDialog"/>

  </div>
</template>
<script>
import FilterTool from '@/components/Tool/filter';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import RecordDialog from './recordDialog';
import DealDialog from './dealDialog';
import { getAfterSaleList, deleteAfterSale } from '@/api/mengli';
import { formatRefundsStatus, formatReturnGoods, formatGoodsStatus, formatDealStatus, formatRebates } from '@/filters/status';
import { mapState } from 'vuex';
import TableAdaptive from '@/mixins/tableAdaptive';
import tableSelections from '@/mixins/tableSelections';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';
import ElMessage from '@/utils/message';
import { verificationOptions } from '@/views/project/model/selectData';
import mobileTable from '@/mixins/mobileTable';

export default {
  components: { FilterTool, EmptyPlaceholder, createBtn, MoreOpeator, DealDialog, RecordDialog },
  filters: {
    formatRefundsStatus,
    formatReturnGoods,
    formatGoodsStatus,
    formatDealStatus,
    formatRebates
    /* orderDeliveryStatus(type) {
      const obj = {
        '0': '待出库',
        '1': '已出库',
        '-1': '库存不足'
      };
      return obj[String(type)] || '--';
    } */
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      // filterTagShow: true,
      isBatchHandel: false,
      tableRefName: 'afterSaleRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      showDealDialog: false,
      dealData: {},
      showRecordDialog: false,
      recordData: {
        orderNum: '',
        cost: '',
        totalCost: '',
        inventoryCount: ''
      },
      verificationOptions,
      paramsObj: {
        orderNum: ''
      },
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      listLoading: false,
      screenWidth: null,
      rangeKeyArr: [{
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time',
        addTime: true
      }],
      // arrayKeyArr: ['orderStatus'],
      sortType: '',
      sortName: '',
      isUmyTable: true,
      selectOrderList: [],
      ids: '',
      orderTypeOption: [
        { value: '', label: '全部' },
        { value: 0, label: '线上' },
        { value: 1, label: '线下' }
      ],
      orderStatusOption: [
        { value: '', label: '全部' },
        { value: 5, label: '正常销售订单' },
        { value: 0, label: '等待买家付款' },
        { value: 1, label: '买家已付款' },
        { value: 2, label: '卖家已发货' },
        { value: 3, label: '交易成功' },
        { value: 4, label: '交易关闭' },
        { value: 6, label: '退款中的订单' }
      ],
      refundsStatusOptions: [
        { value: 0, label: '进行中的订单' },
        { value: 1, label: '退款待处理' },
        { value: 2, label: '已拒绝退款' },
        { value: 3, label: '待买家发货' },
        { value: 4, label: '待商家收货' },
        { value: 5, label: '退款关闭' },
        { value: 6, label: '退款成功' },
        { value: 7, label: '退款完结' }
      ],
      returnGoodsOptions: [
        { value: 0, label: '仅退款' },
        { value: 1, label: '退货退款' },
        { value: 2, label: '维修换货' }
      ],
      goodsStatusOptions: [
        { value: 0, label: '未发货' },
        { value: 1, label: '未收到发货' },
        { value: 2, label: '已收到货' },
        { value: 3, label: '已寄回' }
      ],
      dealStatusOptions: [
        { value: 1, label: '待处理' },
        { value: 2, label: '待盘点' },
        { value: 3, label: '已入库' }
      ]
      /* orderDeliveryStatus: [
        { value: '', label: '全部' },
        { value: 0, label: '待出库' },
        { value: 1, label: '已出库' },
        { value: -1, label: '库存不足' }
      ], */
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    filterList() {
      const arr = [
        { keyword: 'systemSn', name: '退货编号(系统)', type: 'input', labelWidth: '110px' },
        { keyword: 'orderNum', name: '订单编号', type: 'input', labelWidth: '80px' },
        { keyword: 'taobaoSn', name: '退货编号(淘宝)', type: 'input', labelWidth: '110px' },
        { keyword: 'goodsCoding', name: 'SKU编码', type: 'input', labelWidth: '80px' },
        { keyword: 'title', name: '标题', type: 'input', labelWidth: '110px' },
        { keyword: 'creator', name: '创建人', type: 'input', labelWidth: '80px' },
        { keyword: 'createTime', name: '创建时间', type: 'rangeDate', timeType: 'daterange', labelWidth: '110px' },
        { keyword: 'refundsStatus', name: '退款状态', type: 'select', options: this.refundsStatusOptions },
        { keyword: 'returnsStatus', name: '退货状态', type: 'select', options: this.returnGoodsOptions },
        { keyword: 'goodsStatus', name: '货物状态', type: 'select', options: this.goodsStatusOptions },
        { keyword: 'dealStatus', name: '处理状态', type: 'select', options: this.dealStatusOptions }
      ];
      return arr;
    }
  },
  created() {
    this.screenWidth = screen.width;
    if (this.$route.query.orderNum) {
      this.paramsObj.orderNum = this.$route.query.orderNum;
      this.fetchData();
    } else {
      this.fetchData(true);
    }
  },
  methods: {
    hasRouteAuth,
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      // 时间处理
      paramsRangeFormat(this.rangeKeyArr, params);
      // paramsAryToStr(this.arrayKeyArr, params);
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      params.page = this.page;
      params.perPage = this.perPage;
      this.listLoading = true;
      getAfterSaleList(params).then(({ data }) => {
        // 该创建时间返回的字符串，要单独处理
        data.items.forEach(item => {
          item.createTime && (item.createTime = item.createTime.replace(/-/g, '/'));
          item.deliveryTime && (item.deliveryTime = item.deliveryTime.replace(/-/g, '/'));
        });
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
        this.page = data.page;
        this.perPage = data.perPage;
        if (this.setSelectRow) this.setSelectRow(data.items);
      }).catch(e => {
        console.error(e);
        this.listLoading = false;
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.queryClick();
    },
    exportBeforeExport() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      // 时间处理
      paramsRangeFormat(this.rangeKeyArr, params);
      // paramsAryToStr(this.arrayKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.ids = this.ids;
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'projectExportRef');
      }
    },
    toCommerceOrder(row) {
      if (!row.orderId) return;
      const routeUrl = this.$router.resolve({
        name: 'mengliOrderDetail',
        params: { id: row.orderId },
        query: { type: 2 }
      });
      window.open(routeUrl.href, '_blank');
    },
    toCreate() {
      this.$router.push({
        name: 'afterSaleAdd',
        query: { type: 3 }
      });
    },
    toDetail(row) {
      this.$router.push({
        name: 'afterSaleDetail',
        params: { id: row.id },
        query: { type: 3 }
      });
    },
    toEdit(row) {
      this.$router.push({
        name: 'afterSaleEdit',
        params: { id: row.id },
        query: { type: 3 }
      });
    },
    handelDelete(id) {
      showModal('是否确定要删除退货单记录', '', {
        cancelButtonText: '取消',
        lockScroll: false,
        iconClass: 'del-icon'
      }).then(() => {
        deleteAfterSale(id).then(res => {
          ElMessage.success('删除成功');
          this.resetItemSelected(id);
          this.fetchData();
        }).catch(err => {
          console.log(err);
          ElMessage.error(err);
        });
      });
    },
    batchReturn() {
      if (!this.multipleSelectionAll.length) {
        ElMessage.warning('请选择数据！');
        return;
      }
      this.dealData = { ids: this.ids };
      this.showDealDialog = true;
      this.isBatchHandel = true;
    },
    openDealDialog(row) {
      // 判断权限
      if (!this.hasRouteAuth('mengli:inventory:stockTake')) {
        ElMessage.warning('权限不足，请联系管理员！');
        return;
      }
      // 状态为已寄回且填了数量和SKU编码则直接打开待处理弹窗
      // if (row.goodsStatus === 3 && row.goodsCoding && row.number) {
      if (row.dealStatus === 2) {
        this.recordData = {
          id: row.mengliStockBatchId,
          orderNum: row.orderNum,
          cost: row.goodsCost,
          totalCost: row.totalCost * row.number,
          inventoryCount: row.number
        };
        this.showRecordDialog = true;
      } else if (row.dealStatus === 0 || row.dealStatus === 1) {
        this.dealData = {
          ids: row.id,
          taobaoSn: row.taobaoSn,
          orderNum: row.orderNum,
          goodsStatus: row.goodsStatus,
          goodsCoding: row.goodsCoding,
          warehouseId: row.warehouseId,
          returnsCount: row.number
        };
        this.showDealDialog = true;
      }
    },
    closeDealDialog(val) {
      // 不需要重新请求数据，直接赋值数据
      if (val && val !== 200) {
        for (let i = 0; i < this.list.items.length; i++) {
          if (this.list.items[i].id === this.dealData.ids) {
            // 将状态修改为已寄回
            if (val.mengliStockBatchId) {
              this.list.items[i].dealStatus = 2;
              this.list.items[i].goodsStatus = val.goodsStatus;
              this.list.items[i].mengliStockBatchId = val.mengliStockBatchId;
              this.list.items[i].number = val.number;
              this.list.items[i].goodsCost = val.goodsCost;
            } else {
              // 状态修改为非已寄回
              this.list.items[i].goodsStatus = val.goodsStatus;
              this.list.items[i].dealStatus = 0;
            }
            this.showDealDialog = false;
            return;
          }
        }
      } else if (val === 200) {
        this.fetchData(true);
        this.clearMixinSelection();
      }
      this.isBatchHandel = false;
      this.showDealDialog = false;
    },
    openRecordDialog(data) {
      this.recordData = data;
      this.showRecordDialog = true;
    },
    closeRecordDialog(val) {
      this.showRecordDialog = false;
      if (val) {
        this.fetchData();
      }
    },
    tableSelectionChange(e) {
      this.ids = e.map(item => {
        return item.id;
      }).join(',');
    }
  }
};
</script>
<style lang="scss" scoped>
.opeator-bar {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
}
.batch-operation {
  display: flex;
  flex: 1;
  .el-button {
    margin-right: 10px;
  }
}
.mengli-commerce-order {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 20px 55px 20px;
  .system-btn {
    display: flex;
    align-items: center;
    width: 180px;
    justify-content: flex-end;
    .btn-right-item {
      margin-right: 8px;
    }

  }
  .order-num {
    color: #406EFF;
  }
}
.el-dropdown-link {
  display: block;
  position: relative;
  padding-left:6px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
.light-word {
  color: #406EFF;
  cursor: pointer;
}
</style>
